var url="https://detail.tmall.com/item.htm?spm=a220m.1000858.1000725.8.48ff1f67mcD1VC&id=541017907539&skuId=3552785825598&user_id=2457021025&cat_id=2&is_b=1&rn=9d1cc539927d5f268d9d4811052ab121";
var url="https://detail.tmall.com/item.htm?spm=a220m.1000858.1000725.1.613d605a3QsWZ2&id=526956365475&skuId=3745502186464&areaId=340100&user_id=92042735&cat_id=2&is_b=1&rn=9267495f143a35040bd57acca4658ff4&sm=true&smToken=a32d486a9d334f2faa647ab9c60cf3d6&smSign=ngvBD0f1tjtfpfmqfMYcig==";
var fs=require('fs');
var page = require('webpage').create();
var retJsonpObj = null;

fs.makeTree('contents');
page.captureContent = [ /.*/ ];
page.settings.loadImages = false;

page.onResourceReceived = function(response) {
	if(response.url.indexOf('initItemDetail')>-1){
		//这里回调setMdskip方法
		eval(response.body);
	}
};

page.open(url,function(status){
	var analyzeObj = page.evaluate(function(){
		var scriptObj = null;
		var poc = function(str){
			//console.log(str);
		};

		var setConfig = function(obj){
			//console.log("setConfig run");
		};

		var Setup = function(obj){
			//console.log("setConfig run");
			scriptObj = obj;
		};

		//页面中dom提取的信息=========================================================
		var objArr = [];
		var dls = document.querySelectorAll("div.tb-sku > dl.tm-sale-prop");  //查找所有dl
		for(var a=0;a<dls.length;a++){
			var dlElement = dls[a];
			var dt = dlElement.querySelector("dt"); //查找属性类别
			
			var dataValues = dlElement.querySelectorAll("dd > ul > li");  //所有data-value
			var dataValueArr = [];
			for(var b=0;b<dataValues.length;b++){
			var dataValue = dataValues[b].getAttribute("data-value");
			var title = dataValues[b].querySelector("a > span").textContent;
			dataValueArr[b] = {key:dataValue,value:title};
			}
			objArr[a] = {attrTypes:dt.textContent,dataValues:dataValueArr};
		}

		//页面中script中提取的信息=======================================================
		var jsList = document.querySelectorAll("script");	//所有js
		for(var i=0;i<jsList.length;i++){
			var content = jsList[i].textContent;
			if(content.indexOf("TShop.setConfig")>-1 && content.indexOf("detail")>-1){
				var newContent = content.replace(/TShop\./g,'');
				eval(newContent);
			}else{
				continue;
			}
		}

		var obj = {pageScriptObj:scriptObj,detailAttr:objArr}
		return obj;
	});
	var retObj = {};
	retObj.jsonpObj = retJsonpObj;
	retObj.analyzeObj = analyzeObj;
	console.log(JSON.stringify(retObj));
	//fs.write('result.json',JSON.stringify(retObj));
	phantom.exit();
});
		
/**
 *https://mdskip.taobao.com/core/initItemDetail.htm 请求返回的jsonp回调方法，这里再次回调 
 * @param {jsonp返回的真实价格数据} obj 
 * 
 */
function setMdskip(obj){
	retJsonpObj = obj;
}

